package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.Res
import com.jiangnan.repository.PaymentRepository
import kotlinx.coroutines.launch
import java.math.BigDecimal

class RechargeViewModel : ViewModel() {
  private val repo = PaymentRepository()

  private val _balance = MutableLiveData<BigDecimal>()
  val balance: LiveData<BigDecimal> = _balance

  private val _error = MutableLiveData<String>()
  val error: LiveData<String> = _error

  private val _toastMessage = MutableLiveData<String>()
  val toastMessage: LiveData<String> = _toastMessage

  fun recharge(userId: Long, amount: BigDecimal) {
    viewModelScope.launch {
      try {
        val res: Res<BigDecimal> = repo.recharge(userId, amount)
        if (res.code == 1 && res.data != null) {
          _balance.value = res.data!!
          _toastMessage.postValue("充值成功")
        } else {
          _error.value = res.msg
        }
      } catch (e: Exception) {
        _error.value = e.message
      }
    }
  }
}